package com.tetris

import android.graphics.BitmapFactory
import android.os.Bundle
import android.widget.Toast

import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout

import com.tetris.Game.Status
import com.tetris.ui.theme.TetrisTheme

// 主活动
class MainActivity: ComponentActivity() {
    private lateinit var mGame: Game    // 游戏

    /**
     * 界面布局。
     */
    @Composable
    fun Greeting() {
        // 获取屏幕尺寸
        val density = LocalDensity.current.density
        val screenWidthPx = resources.displayMetrics.widthPixels
        val screenHeightPx = resources.displayMetrics.heightPixels

        // 计算格的尺寸
        Const.GRID_SIZE = screenWidthPx.toFloat() / (Const.PADDING_LEFT + Const.GAME_BOARD_GRID_COUNT_H +
            Const.PADDING_MIDDLE + Const.PREVIEW_GRID_COUNT_H + Const.PADDING_RIGHT)
        val gridSizeDp = Const.GRID_SIZE / density

        // 计算游戏区域尺寸和位置
        val gameBoardWidthDp = Const.GRID_SIZE * Const.GAME_BOARD_GRID_COUNT_H / density
        val gameBoardHeightDp = Const.GRID_SIZE * Const.GAME_BOARD_GRID_COUNT_V / density
        val gameBoardX = Const.GRID_SIZE / density
        val gameBoardY = (screenHeightPx - Const.GRID_SIZE * Const.GAME_BOARD_GRID_COUNT_V) * 0.5f / density

        // 计算预览区域尺寸和位置
        val preViewWidthPx = Const.GRID_SIZE * Const.PREVIEW_GRID_COUNT_H
        val preViewHeightPx = Const.GRID_SIZE * Const.PREVIEW_GRID_COUNT_V
        val previewWidthDp = preViewWidthPx / density
        val previewHeightDp = preViewHeightPx / density
        val previewX = gameBoardWidthDp + gridSizeDp * 2
        val previewY = gameBoardY

        // 布局
        ConstraintLayout(Modifier
            .fillMaxSize()
            .systemBarsPadding()
        ) {
            // 背景图片
            Image(
                painter = painterResource(R.mipmap.main_activity),
                contentDescription = "",
                modifier = Modifier.fillMaxSize(),
                contentScale = ContentScale.FillBounds
            )

            val (statusBar) = this.createRefs()
            var bitmap = BitmapFactory.decodeResource(resources, R.mipmap.button_transform)
            val btnPlayWidth = bitmap.width / density
            val btnPlayHeight = bitmap.height / density

            // 游戏区域
            mGame.GameBoard(Modifier
                .size(gameBoardWidthDp.dp, gameBoardHeightDp.dp)
                .offset(gameBoardX.dp, gameBoardY.dp)
                .background(Const.GAME_BOARD_COLOR)
            )

            // 预览区域
            mGame.Preview(
                modifier = Modifier
                    .size(previewWidthDp.dp, previewHeightDp.dp)
                    .offset(previewX.dp, previewY.dp)
                    .background(Const.PREVIEW_COLOR),
                width = preViewWidthPx,
                height = preViewHeightPx
            )

            // "变形"按钮
            val btnTransformX = previewX + previewWidthDp - btnPlayWidth * 2 - Const.MAIN_ACTIVITY_CTRL_PADDING.value
            val btnTransformY = gameBoardY + gameBoardHeightDp - btnPlayHeight
            IconButton(mGame.transformBlock, Modifier.offset(btnTransformX.dp, btnTransformY.dp)) {
                Image(BitmapFactory.decodeResource(resources, R.mipmap.button_transform).asImageBitmap(), "")
            }

            // "加速下落"按钮
            val btnDownX = previewX + previewWidthDp - btnPlayWidth
            val btnDownY = btnTransformY
            IconButton(mGame.moveBlockDown, Modifier.offset(btnDownX.dp, btnDownY.dp)) {
                Image(BitmapFactory.decodeResource(resources, R.mipmap.button_down).asImageBitmap(), "")
            }

            // "向左"按钮
            val btnLeftX = btnTransformX
            val btnLeftY = btnTransformY - btnPlayHeight - Const.MAIN_ACTIVITY_CTRL_PADDING.value
            IconButton(mGame.moveBlockLeft, Modifier.offset(btnLeftX.dp, btnLeftY.dp)) {
                Image(BitmapFactory.decodeResource(resources, R.mipmap.button_left).asImageBitmap(), "")
            }

            // "向右"按钮
            val btnRightX = btnDownX
            val btnRightY = btnLeftY
            IconButton(mGame.moveBlockRight, Modifier.offset(btnRightX.dp, btnRightY.dp)) {
                Image(BitmapFactory.decodeResource(resources, R.mipmap.button_right).asImageBitmap(), "")
            }

            bitmap = BitmapFactory.decodeResource(resources, R.mipmap.button_music_play)
            val btnWHScale = bitmap.height.toFloat() / bitmap.width.toFloat()
            val btnControlWidth = previewWidthDp
            val btnControlHeight = btnControlWidth * btnWHScale

            // "播放音乐"按钮
            val btnMusicX = previewX
            val btnMusicY = btnLeftY - btnPlayHeight - Const.MAIN_ACTIVITY_CTRL_PADDING.value
            IconButton(
                onClick = mGame.playMusic,
                modifier = Modifier
                    .size(btnControlWidth.dp, btnControlHeight.dp)
                    .offset(btnMusicX.dp, btnMusicY.dp)
            ) {
                val bitmapResId = if (mGame.enableMusic) R.mipmap.button_music_stop else R.mipmap.button_music_play
                Image(BitmapFactory.decodeResource(resources, bitmapResId).asImageBitmap(), "", Modifier.fillMaxSize())
            }

            // "暂停"按钮
            val btnPauseX = previewX
            val btnPauseY = btnMusicY - btnPlayHeight - Const.MAIN_ACTIVITY_CTRL_PADDING.value
            IconButton(
                onClick = mGame.pause,
                modifier = Modifier
                    .size(btnControlWidth.dp, btnControlHeight.dp)
                    .offset(btnPauseX.dp, btnPauseY.dp),
                enabled = mGame.status != Status.END && mGame.status != Status.LOST || mGame.status != Status.WON
            ) {
                val bitmapResId = when (mGame.status) {
                    Status.PAUSED -> R.mipmap.button_resume
                    Status.PLAYING -> R.mipmap.button_pause
                    else -> R.mipmap.button_pause_disabled
                }
                Image(BitmapFactory.decodeResource(resources, bitmapResId).asImageBitmap(), "", Modifier.fillMaxSize())
            }

            // "开始"按钮
            val btnStartX = previewX
            val btnStartY = btnPauseY - btnPlayHeight - Const.MAIN_ACTIVITY_CTRL_PADDING.value
            IconButton(
                onClick = mGame.start,
                modifier = Modifier
                    .size(btnControlWidth.dp, btnControlHeight.dp)
                    .offset(btnStartX.dp, btnStartY.dp)
            ) {
                Image(BitmapFactory.decodeResource(resources, R.mipmap.button_start).asImageBitmap(), "", Modifier.fillMaxSize())
            }

            // 状态栏
            Row(Modifier
                .fillMaxWidth()
                .constrainAs(statusBar) {
                    start.linkTo(parent.start)
                    bottom.linkTo(parent.bottom)
                }
            ) {
                // "难度"标签
                Text(
                    text = super.getString(R.string.IDS_DIFFICULTY, mGame.difficulty),
                    modifier = Modifier
                        .weight(0.5f)
                        .padding(Const.MAIN_ACTIVITY_CTRL_PADDING),
                    color = Color.White)

                // "得分"标签
                Text(
                    text = super.getString(R.string.IDS_SCORE, mGame.score),
                    modifier = Modifier
                        .weight(0.5f)
                        .padding(Const.MAIN_ACTIVITY_CTRL_PADDING),
                    color = Color.White)
            }

            // 吐司窗口
            if (mGame.status == Status.WON) {
                Toast.makeText(this@MainActivity, super.getString(R.string.IDS_WON), Toast.LENGTH_LONG).show()
            } else if (mGame.status == Status.LOST) {
                Toast.makeText(this@MainActivity, super.getString(R.string.IDS_LOST), Toast.LENGTH_LONG).show()
            }
        }
    }

    /**
     * 创建事件的响应方法。
     * @param savedInstanceState    保存的实例状态
     */
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        this.enableEdgeToEdge()

        // 初始化成员
        mGame = Game(this)

        // 设置内容
        this.setContent {
            TetrisTheme {
                this.Greeting()
            }
        }
    }

    /**
     * 暂停事件的响应方法。
     */
    public override fun onPause() {
        super.onPause()

        if (mGame.status == Status.PLAYING) {
            mGame.pause()
        }
    }
}
